package serveur.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

import javax.imageio.ImageIO;

public class ImageSynchronizeServeur {

	private String[] listeImageFileName;
	private File repertoire;
	
	public ImageSynchronizeServeur (String dirRep) {
		this.repertoire = new File(dirRep);
		System.out.println("repertoire :"+ dirRep);
		this.initListeImagesFileName(this.repertoire);
		
	}
	
	public void envoiImage(Socket client) throws IOException{
		int i = 0;
		BufferedOutputStream output = null;
		output = new BufferedOutputStream(client.getOutputStream());
		
		while (true) {
			
			File imageFile = null;
			imageFile = new File(this.repertoire+"/"+this.listeImageFileName[i]);
			
		
			String locFormat = this.listeImageFileName[i].substring(this.listeImageFileName[i].indexOf(".") + 1, this.listeImageFileName[i].length());
			System.out.println(locFormat);
			try {
				

				System.out.println("envoi "+imageFile.getAbsolutePath());

				FileInputStream fis = new FileInputStream(imageFile);
			

				BufferedImage locImage = ImageIO.read(fis);
				ByteArrayOutputStream locStream = new ByteArrayOutputStream((int) (imageFile.length() + 1));
				ImageIO.write(locImage, locFormat, locStream);
				byte[]bytes = null;
				bytes = locStream.toByteArray();
				output.write(bytes);
				output.flush();
				locImage.flush();
				locStream.flush();
				i++;

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (i == this.listeImageFileName.length) {
				break;
			}
		}
	}
	
	public void initListeImagesFileName (File repertoire) {
		String [] tabtmp = new String [repertoire.list().length-1];
		tabtmp = repertoire.list();
		
		this.listeImageFileName = new String[tabtmp.length-1];
	
		for(int i = 0 ; i < this.listeImageFileName.length;i++){
			this.listeImageFileName[i] = tabtmp[i+1];
		}

	}
	
	public String[] getListeImageFileName() {
		return this.listeImageFileName;
	}
}
